package com.findMoneyGame.pages.game.states {
	import flash.events.Event;

	import com.findMoneyGame.pages.ClosablePage;
	import com.findMoneyGame.pages.preloading.ThePreloader;
	import com.findMoneyGame.pages.game.states.*;
	import com.findMoneyGame.pages.game.GameLevelPage;
	import com.findMoneyGame.models.GameLevel;

	public class LoadingState extends GameLevelPageState {
		private static const FETCHING_GAME_DATA_STAGE = 0;
		private static const LOADING_GAME_IMAGE_STAGE = 1;

		private var preloader : ThePreloader;
		private var stage : int;

		public function LoadingState (gameLevelPage : GameLevelPage) {
			super(gameLevelPage);
			gameLevelPage.addEventListener(
				ClosablePage.CLOSE_EVENT, 
				function (e : Event) { gameLevelPage.removeEventListener(Event.ENTER_FRAME, enterFrame); });
		}

		public function start () {
			// TODO: разместить прелоадер по-человечески
			gameLevelPage.addChild(preloader = new ThePreloader(1000));
			preloader.width = gameLevelPage.imageWidth;
			preloader.height = gameLevelPage.imageHeight;
			stage = FETCHING_GAME_DATA_STAGE;
			gameLevel = new GameLevel(user.level == 0 ? 0 : user.level + 1);
			var fetchDataComplete = function (e : Event) {
				stage = LOADING_GAME_IMAGE_STAGE;
				gameLevel.beginLoadImage(loadImageComplete, loadImageError);
			}
			var fetchDataError = function (e : Event) {
				// TODO
			}
			gameLevel.beginFetchData(fetchDataComplete, fetchDataError);
			gameLevelPage.addEventListener(Event.ENTER_FRAME, enterFrame);
		}

		private function enterFrame (e : Event) {
			if (stage == FETCHING_GAME_DATA_STAGE) {
				var progress = (gameLevel.bytesTotal == 0 ? 0 : gameLevel.bytesLoaded) / 4;
				preloader.setPreloadingPercent(progress);
			} else if (stage == LOADING_GAME_IMAGE_STAGE) {
				progress = (gameLevel.bytesTotal == 0 ? 0 : gameLevel.loadingPercent) * 3 / 4;
				preloader.setPreloadingPercent(1 / 4 + progress);
			}
		}
		private function loadImageComplete (e : Event) {
			gameLevelPage.removeEventListener(Event.ENTER_FRAME, enterFrame);
			gameLevelPage.removeChild(preloader);
			new PlayingState(gameLevelPage).start();
		}
		private function loadImageError (e : Event) {
			// TODO
		}
	}
}